package com.yxh.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yxh.base.PageEntity;
import com.yxh.common.other.Const;
import com.yxh.dao.UnitMapper;
import com.yxh.exception.UnitException;
import com.yxh.exception.UserException;
import com.yxh.pojo.Unit;
import com.yxh.service.UnitService;
import com.yxh.util.SnowflakeIdWorker;
import com.yxh.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import static com.yxh.util.APIErrorCode.PARAMS_INVALID;
import static com.yxh.util.APIErrorCode.*;

/**
 * Created by 32988 on 2018/6/1.
 */
@Service("unitService")
public class UnitServiceImpl implements UnitService {


    @Autowired
    private UnitMapper unitMapper;


    public int save(Unit unit) {
        this.checkValid(unit.getName(), Const.UNIT_NAME);
        unit.setId(SnowflakeIdWorker.creatId());
        int count = unitMapper.insert(unit);
        if (count == 0) {
            throw new UserException(REGISTER_ERROR);
        }
        return count;
    }

    public PageInfo getInformation(Unit unit, Integer limit, Integer offset) {
        PageHelper.startPage(limit, offset);
        List<Map<String,Object>> unitList = unitMapper.selectByUnit(unit);

        PageInfo pageInfo = new PageInfo(unitList);
        pageInfo.setList(unitList);
        return pageInfo;
    }

    public int update(Unit unit) {
        int count = unitMapper.updateByPrimaryKeySelective(unit);
        return count;
    }

    public int delete(String id) {
        if(!StringUtil.isEmpty(id)){
            String [] arr = id.split(",");
            int count = unitMapper.deleteByIds(arr);
            if (count == 0) {
                throw new UnitException(PARAMS_INVALID);
            }
        }
        return 0;
    }

    public Boolean checkValid(String str, String type) {
        if (StringUtils.isNotBlank(type)) {
            if (Const.UNIT_NAME.equals(type)) {
                int count = unitMapper.checkName(str);
                if (count > 0) {
                    throw new UnitException(UNIT_EXIST);
                }
            }
        } else {
            throw new UnitException(PARAMS_INVALID);
        }
        return true;
    }


    public void batchDelete(List<Unit> records) {

    }

    public Unit get(String id) {
        return null;
    }

    public Unit get(Unit record) {
        return null;
    }

    public List<Unit> getList(Unit record) {
        return null;
    }

    public List<Unit> getAllList(Unit record) {
        return null;
    }

    public List<Unit> getListPage(PageEntity<Unit> record) {
        return null;
    }
}
